package com.kang.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.kang.pojo.AjaxResult;
import com.kang.pojo.Audit;
import com.kang.pojo.PurchaseItem;
import com.kang.pojo.PurchaseOrderItem;
import com.kang.pojo.PurchaseRequest;
import com.kang.service.AssistService;
import com.kang.service.AuditService;
import com.kang.service.IntemInformationService;
import com.kang.service.PurchaseRequestService;
import com.kang.service.UserService;
import com.kang.service.WarehouseService;
import com.kang.until.FileUtil;
import com.kang.until.PDFUtil;
import com.kang.until.purchaseOrderExcelInput;
import com.vonechina.entity.page.PurchaseRequestItemPage;
import com.vonechina.entity.page.PurchaseRequestPage;

import jxl.Sheet;
import jxl.Workbook;

/**
 * 采购申请控制层
 * 
 * @author zs614
 *
 */
@Controller
@RequestMapping("purchaseRequest")
@SessionAttributes({ "purchaseRequestPage" })
public class PurchaseRequestController extends com.kang.controller.Controller {
	/**
	 * 采购申请服务层
	 */
	@Resource
	private PurchaseRequestService requestService;
	/**
	 * 通用服务层
	 */
	@Resource
	private AssistService assistService;
	/**
	 * 物品服务层
	 */
	@Resource
	private IntemInformationService itemService;
	/**
	 * 用户服务层
	 */
	@Resource
	private UserService userService;
	/**
	 * 仓库服务层
	 */
	@Resource
	private WarehouseService warehouseService;
	/**
	 * 审核服务层
	 */
	@Resource
	private AuditService auditService;

	/**
	 * 分页查看采购申请
	 * 
	 * @param session
	 * @param model
	 * @param purchaseRequestPage
	 *            搜索条件自动封装
	 * @return
	 */
	@RequestMapping("listPurchaseRequest")
	public String listPurchaseRequest(HttpSession session, Model model, PurchaseRequestPage purchaseRequestPage) {
		initRight(session);
		if (checkRight("查看采购申请") != SUCCESS && checkRight("查看全部采购申请") != SUCCESS) {
			return "basic/noRight";
		}
		if (checkRight("查看全部采购申请") == SUCCESS) {
			purchaseRequestPage.setApplicantID(null);
		} else {
			purchaseRequestPage.setApplicantID(userID);
		}
		List<PurchaseRequest> pr = requestService.listPurchaseRequest(purchaseRequestPage);
		model.addAttribute("prList", pr);
		model.addAttribute("organizations", assistService.listOrganization());
		model.addAttribute("cruiseList", assistService.listCruise());
		model.addAttribute("isAdd", checkRight("新增采购申请") == SUCCESS);
		purchaseRequestPage.setPageUrl("purchaseRequest/listPurchaseRequest.do");
		model.addAttribute("page", purchaseRequestPage);
		return "business/purchaseRequest/listPurchaseRequest";
	}

	/**
	 * 前往新增采购申请界面
	 * 
	 * @param session
	 * @param model
	 * @return 返回jsp页面
	 */
	@RequestMapping("toAdd")
	public String toAddPurchaseRequest(HttpSession session, Model model) {
		initRight(session);
		if (checkRight("新增采购申请") != SUCCESS) {
			return "basic/noRight";
		}
		model.addAttribute("isEdit", false);
		model.addAttribute("organizations", assistService.listOrganization());
		model.addAttribute("cruiseList", assistService.listCruise());
		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());
		return "business/purchaseRequest/addRequestDetail";
	}

	/**
	 * 新增采购申请
	 * 
	 * @param session
	 * @param pur
	 *            采购申请实体类自动封装
	 * @param itemIds
	 *            采购申请物品ID数组
	 * @param itemNumber
	 *            采购申请物品数量数组
	 * @return 返回json字符串
	 */
	@RequestMapping("add")
	@ResponseBody
	public String addPurchaseRequest(HttpSession session, PurchaseRequest pur, Integer[] itemIds,
			Integer[] itemNumber) {
		initRight(session);
		AjaxResult result = new AjaxResult();
		if (checkRight("新增采购申请") != SUCCESS) {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		pur.setApplicationNo(requestService.generatoApplicationNo());
		pur.setApplicantID((Integer) session.getAttribute("userID"));
		pur.setLastPersonID((Integer) session.getAttribute("userID"));
		pur.setCreateDate(new Date());
		pur.setLastProcessingTime(new Date());
		pur.setpNumber(itemIds.length);
		requestService.insertSelective(pur);
		if (pur.getPurchaseRequisitionID() == null || pur.getPurchaseRequisitionID() <= 0)
			return JSON.toJSONString(result);
		for (int i = 0; i < itemIds.length; i++) {
			PurchaseItem item = new PurchaseItem();
			item.setPurchaseRequisitionID(pur.getPurchaseRequisitionID());
			item.setItemInformationID(itemIds[i]);
			item.setNumber(itemNumber[i]);
			requestService.addItem(item);
		}
		if (pur.getStatus() == 1) {
			Audit audit = new Audit();
			audit.setAuditType(1);
			audit.setSourceID(pur.getPurchaseRequisitionID());
			audit.setLastPersonID(userID);
			audit.setMoney("0");
			auditService.addAudit(audit);
			requestService.updateStatus(pur.getPurchaseRequisitionID(), 2);
		}
		result.setResult("success");
		return JSON.toJSONString(result);
	}

	/**
	 * 复制已有采购申请，生成新的未提交采购申请
	 * 
	 * @param session
	 * @param purchaseRequestid
	 *            采购申请ID
	 * @return 返回json字符串
	 */
	@RequestMapping("copy")
	@ResponseBody
	public String copyPurchaseRequest(HttpSession session, Integer purchaseRequestid) {
		initRight(session);
		AjaxResult result = new AjaxResult();
		if (checkRight("新增采购申请") != SUCCESS) {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		PurchaseRequest pur = requestService.selectPurchaseRequestById(purchaseRequestid);
		pur.setApplicationNo(requestService.generatoApplicationNo());
		pur.setApplicantID((Integer) session.getAttribute("userID"));
		pur.setLastPersonID((Integer) session.getAttribute("userID"));
		pur.setCreateDate(new Date());
		pur.setLastProcessingTime(new Date());
		pur.setStatus(0);
		List<PurchaseItem> items = requestService.listItem(purchaseRequestid, pur.getWarehouseManagementID());
		pur.setpNumber(items.size());
		requestService.insertSelective(pur);
		if (pur.getPurchaseRequisitionID() == null || pur.getPurchaseRequisitionID() <= 0)
			return JSON.toJSONString(result);
		for (int i = 0; i < items.size(); i++) {
			PurchaseItem item = items.get(i);
			item.setPurchaseRequisitionID(pur.getPurchaseRequisitionID());
			requestService.addItem(item);
		}
		result.setResult("success");
		return JSON.toJSONString(result);
	}

	/**
	 * 采购申请查看可用物品
	 * 
	 * @param itemPage
	 * @return 返回josn字符串
	 */
	@RequestMapping("listNotAddItem")
	@ResponseBody
	public String listNotAddItem(PurchaseRequestItemPage itemPage) {
		List<PurchaseItem> iteminfolist = requestService.listNotInItem(itemPage);
		AjaxResult result = new AjaxResult();
		result.setRows(iteminfolist);
		result.setTotal(itemPage.getRows());
		return JSON.toJSONString(result);
	}

	/**
	 * 查看采购申请详情
	 * 
	 * @param session
	 * @param model
	 * @param purchaseRequisitionID
	 *            采购申请ID
	 * @return 返回jsp页面
	 */
	@RequestMapping("toEdit")
	public String toEditPurchaseRequest(HttpSession session, Model model, Integer purchaseRequisitionID) {
		initRight(session);
		PurchaseRequest pur = requestService.selectPurchaseRequestById(purchaseRequisitionID);
		if (pur.getApplicantID() == userID && checkRight("新增采购申请") == SUCCESS) {
			model.addAttribute("isEdit", true);
		} else if (checkRight("编辑全部采购申请") == SUCCESS) {
			model.addAttribute("isEdit", true);
		} else {
			model.addAttribute("isEdit", false);
		}
		model.addAttribute("pur", pur);
		model.addAttribute("isAdd", checkRight("新增采购申请") == SUCCESS);
		model.addAttribute("organizations", assistService.listOrganization());
		model.addAttribute("cruiseList", assistService.listCruise());
		model.addAttribute("itemList", requestService.listItem(purchaseRequisitionID, pur.getWarehouseManagementID()));
		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());
		return "business/purchaseRequest/editRequestDetail";
	}

	/**
	 * 更新采购申请信息
	 * 
	 * @param session
	 * @param pur
	 *            采购申请
	 * @param itemIds
	 *            采购申请物品ID数组
	 * @param itemNumber
	 *            采购申请物品数量数组
	 * @return 返回json字符串
	 */
	@RequestMapping("update")
	@ResponseBody
	public String updatePurchaseRequest(HttpSession session, PurchaseRequest pur, Integer[] itemIds,
			Integer[] itemNumber) {
		initRight(session);
		AjaxResult result = new AjaxResult();
		if (requestService.selectPurchaseRequestById(pur.getPurchaseRequisitionID()).getApplicantID() == userID
				&& checkRight("新增采购申请") == SUCCESS) {

		} else if (checkRight("编辑全部采购申请") == SUCCESS) {

		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		pur.setLastPersonID((Integer) session.getAttribute("userID"));
		pur.setLastProcessingTime(new Date());
		pur.setpNumber(itemIds.length);
		requestService.updateByPrimaryKey(pur);
		if (pur.getPurchaseRequisitionID() == null || pur.getPurchaseRequisitionID() <= 0)
			return JSON.toJSONString(result);
		for (int i = 0; i < itemIds.length; i++) {
			PurchaseItem item = new PurchaseItem();
			item.setPurchaseRequisitionID(pur.getPurchaseRequisitionID());
			item.setItemInformationID(itemIds[i]);
			item.setNumber(itemNumber[i]);
			if (requestService.selectItem(item) == null) {
				requestService.addItem(item);
			} else {
				requestService.updateItem(item);
			}
		}
		result.setResult("success");
		return JSON.toJSONString(result);
	}

	/**
	 * 更新并提交采购申请信息
	 * 
	 * @param session
	 * @param pur
	 *            采购申请
	 * @param itemIds
	 *            采购申请物品ID数组
	 * @param itemNumber
	 *            采购申请物品数量数组
	 * @return 返回json字符串
	 */
	@RequestMapping("updateAndSubmit")
	@ResponseBody
	public String updateAndSubmit(HttpSession session, PurchaseRequest pur, Integer[] itemIds, Integer[] itemNumber,
			Integer size) {
		initRight(session);
		AjaxResult result = new AjaxResult();
		if (requestService.selectPurchaseRequestById(pur.getPurchaseRequisitionID()).getApplicantID() == userID
				&& checkRight("新增采购申请") == SUCCESS) {

		} else if (checkRight("编辑全部采购申请") == SUCCESS) {

		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		pur.setLastPersonID((Integer) session.getAttribute("userID"));
		pur.setLastProcessingTime(new Date());
		pur.setpNumber(itemIds.length);
		requestService.updateByPrimaryKey(pur);
		if (pur.getPurchaseRequisitionID() == null || pur.getPurchaseRequisitionID() <= 0)
			return JSON.toJSONString(result);
		for (int i = 0; i < itemIds.length; i++) {
			PurchaseItem item = new PurchaseItem();
			item.setPurchaseRequisitionID(pur.getPurchaseRequisitionID());
			item.setItemInformationID(itemIds[i]);
			item.setNumber(itemNumber[i]);
			if (requestService.selectItem(item) == null) {
				requestService.addItem(item);
			} else {
				requestService.updateItem(item);
			}
		}
		requestService.submitRequest(pur.getPurchaseRequisitionID());
		Audit audit = new Audit();
		audit.setAuditType(1);
		audit.setSourceID(pur.getPurchaseRequisitionID());
		audit.setLastPersonID(userID);
		audit.setMoney("0");
		auditService.addAudit(audit);
		requestService.updateStatus(pur.getPurchaseRequisitionID(), 2);
		result.setResult("success");
		return JSON.toJSONString(result);
	}

	/**
	 * 提交采购申请
	 * 
	 * @param session
	 * @param purchaseRequestid
	 *            采购申请ID
	 * @return 返回json字符串
	 */
	@RequestMapping("submitStatus")
	@ResponseBody
	public String submitStatus(HttpSession session, Integer purchaseRequestid) {
		initRight(session);
		AjaxResult result = new AjaxResult();
		if (requestService.selectPurchaseRequestById(purchaseRequestid).getApplicantID() == userID
				&& checkRight("新增采购申请") == SUCCESS) {

		} else if (checkRight("编辑全部采购申请") == SUCCESS) {

		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		int a = requestService.submitRequest(purchaseRequestid);
		if (a > 0) {
			Audit audit = new Audit();
			audit.setAuditType(1);
			audit.setSourceID(purchaseRequestid);
			audit.setLastPersonID(userID);
			audit.setMoney("0");
			auditService.addAudit(audit);
			requestService.updateStatus(purchaseRequestid, 2);
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}

	/**
	 * 删除未提交采购申请
	 * 
	 * @param session
	 * @param purchaseRequestid
	 *            采购申请ID
	 * @return
	 */
	@RequestMapping("delete")
	@ResponseBody
	public String deletePurchaseRequest(HttpSession session, Integer purchaseRequestid) {
		initRight(session);
		AjaxResult result = new AjaxResult();
		if (requestService.selectPurchaseRequestById(purchaseRequestid).getApplicantID() == userID
				&& checkRight("新增采购申请") == SUCCESS) {

		} else if (checkRight("编辑全部采购申请") == SUCCESS) {

		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		int a = requestService.deleteByPrimaryKey(purchaseRequestid);
		if (a > 0) {
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}

	/**
	 * 导出采购申请PDF文件
	 * 
	 * @param session
	 * @param response
	 * @param purchaseRequisitionID
	 *            采购申请ID
	 * @throws Exception
	 */
	@RequestMapping("download")
	public void downloadPDF(HttpSession session, HttpServletResponse response, Integer purchaseRequisitionID)
			throws Exception {
		initRight(session);
		PurchaseRequest pur = requestService.selectPurchaseRequestById(purchaseRequisitionID);
		if (pur.getApplicantID() == userID && checkRight("新增采购申请") == SUCCESS) {
		} else if (checkRight("编辑全部采购申请") == SUCCESS) {
		} else {
			return;
		}
		List<PurchaseItem> list = requestService.listItem(purchaseRequisitionID, pur.getWarehouseManagementID());
		File file = PDFUtil.buildPurchaseRequestPDF(pur, list);
		FileUtil.download(response, file, file.getName());
	}
	
	
	/**
	 * 导入采购订单Excel文件
	 * 
	 * @param session
	 * @param response
	 * @param purchaseOrderID
	 *            采购订单ID
	 * @throws Exception
	 */
	@RequestMapping("excelInput")
	@SuppressWarnings("unused")
	@ResponseBody
	public String ExcelInputFile(@RequestParam("submitOrder_files") MultipartFile submitOrder_files,HttpSession session,HttpServletRequest request){
		System.out.println("========Excel导入========");
		//判断文件
		String fileName = null;
		String filePath = null;
        if(submitOrder_files!=null && !submitOrder_files.isEmpty()){
        	List<String> numberList = new ArrayList<String>();
        	try {
        		
            	fileName = submitOrder_files.getOriginalFilename();//文件名称
            	filePath = request.getSession().getServletContext().getRealPath("/") + fileName;  
            	System.out.println("===fileName==="+ filePath);
                // 转存文件  
        		submitOrder_files.transferTo(new File(filePath));  
        	}catch(Exception e){
        		e.printStackTrace();
				return "请上传严格按照规定的文件命名格式的文件";
			}
        	
        }	
        List<PurchaseOrderItem> poilist = purchaseOrderExcelInput.parseExcel(filePath);
        for (int i = 0; i < poilist.size(); i++) {
			System.out.println("===list==="+ poilist.get(i));
		}
		return " ";
	}
	
}
